<?php
namespace api\action\contact;

use Yii;
use yii\rest\CreateAction as BaseCreateAction;
use yii\helpers\Url;
use common\helpers\Util;
use api\helpers\JWT;
use common\models\VoteLog;

class CreateAction extends BaseCreateAction
{

    public function run()
    {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }

        /* @var $model \yii\db\ActiveRecord */
        $model = new $this->modelClass([
            'scenario' => $this->scenario,
        ]);

        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        $token = JWT::decode(Yii::$app->request->post('token'));
        $model->openid = $token['openid'];
        $log = VoteLog::find()->where(['openid' => $model->openid])->one();
        if (!$log) {
            Util::error('你还没有投票过', 502);
        }
        
        if (!$model->save()) {
            Util::error(implode(',', $model->firstErrors), 502);
        }
        return $model;
    }

    

}
